from rest_framework import serializers
from system.models import File

class FileSerializer(serializers.ModelSerializer):
    """文件序列化器"""
    
    url = serializers.SerializerMethodField()
    
    class Meta:
        model = File
        fields = ['id', 'file_name', 'file_path', 'file_size', 'file_type', 'create_time', 'url']
        read_only_fields = ['id', 'file_name', 'file_path', 'file_size', 'file_type', 'create_time']

    def get_url(self, obj):
        """获取文件的URL"""
        # 从配置中获取MinIO服务器地址
        from django.conf import settings
        host_port = settings.MINIO_HOST_PORT
        bucket_name = settings.MINIO_BUCKET_NAME
        protocol = 'https' if settings.MINIO_SSL else 'http'
        
        # 构建URL
        url = f"{protocol}://{host_port}/{bucket_name}/{obj.file_path}"
        return url

class FileInfoSerializer(serializers.Serializer):
    """文件信息序列化器，用于API响应"""
    name = serializers.CharField(source='file_name')
    url = serializers.CharField()
